#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/socket.h>

#include <netinet/in.h>
#include <netinet/ip.h>

#include <arpa/inet.h>

/**
 *  @author Kristina Kurian
 *  @usage serv
 *  @date 06-10-2011
*/

#define BUFFER 1024
#define SERV_PORT 9877
#define LISTENQ 1024

int main(int argc, char ** argv) {
  int listenfd;
  int connfd;

  char line[BUFFER];
  
  struct sockaddr_in servaddr;
  listenfd = socket(AF_INET, SOCK_STREAM, 0);
  
  if (listenfd == -1) {
    printf("ERROR: Failed to create socket.\n");
    return 1;
  }
    
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(SERV_PORT);
  
  if (bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1) {
    printf("EEROR: failed to bind\n");
    close(listenfd);
    return 1;
  }
  listen(listenfd, LISTENQ);
  
  int client = 0;
  while ((client = accept(listenfd, NULL, NULL)) != -1 ) {
    int len = recv(client, line, BUFFER, 0);
    if (len > 0) {
      send(client, line, len, 0);
    } else {
      printf("ERROR: Failed to receive.\n");
    }
    close(client);
  }
  close(listenfd);
}
